{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-02-15T07:56:14.588123Z",
     "start_time": "2025-02-15T07:56:14.460403Z"
    }
   },
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils import data\n",
    "import d2l\n",
    "\n",
    "true_w = torch.tensor([2, -3.4])\n",
    "true_b = 4.2\n",
    "features, labels = d2l.synthetic_data(true_w, true_b, 1000)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The autoreload extension is already loaded. To reload it, use:\n",
      "  %reload_ext autoreload\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-15T07:56:16.051231Z",
     "start_time": "2025-02-15T07:56:15.924322Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def load_array(data_arrays, batch_size, is_train=True):\n",
    "    \"\"\"构造一个PyTorch数据迭代器\"\"\"\n",
    "    dataset = data.TensorDataset(*data_arrays)\n",
    "    return data.DataLoader(dataset, batch_size, shuffle=is_train)\n",
    "\n",
    "batch_size = 10\n",
    "data_iter = load_array((features, labels), batch_size)"
   ],
   "id": "6793d4a97bd7482a",
   "outputs": [],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-15T08:08:10.592866Z",
     "start_time": "2025-02-15T08:08:10.414897Z"
    }
   },
   "cell_type": "code",
   "source": "next(iter(data_iter))",
   "id": "da7ebfef4c729404",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[tensor([[ 0.7449, -0.3003],\n",
       "         [ 1.4591, -1.2995],\n",
       "         [ 0.4580, -0.8753],\n",
       "         [-0.6186, -0.3609],\n",
       "         [-1.6542,  0.8926],\n",
       "         [ 1.2184,  0.4058],\n",
       "         [-0.7498, -0.3998],\n",
       "         [ 0.3989,  1.4211],\n",
       "         [ 1.2928, -0.1137],\n",
       "         [-0.6009,  0.4428]]),\n",
       " tensor([[ 6.7146],\n",
       "         [11.5312],\n",
       "         [ 8.0915],\n",
       "         [ 4.2013],\n",
       "         [-2.1353],\n",
       "         [ 5.2562],\n",
       "         [ 4.0663],\n",
       "         [ 0.1691],\n",
       "         [ 7.1707],\n",
       "         [ 1.4949]])]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-15T08:10:25.658103Z",
     "start_time": "2025-02-15T08:10:25.504823Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# nn是神经网络的缩写\n",
    "from torch import nn\n",
    "\n",
    "net = nn.Sequential(nn.Linear(2, 1))"
   ],
   "id": "b96694d360a59d28",
   "outputs": [],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-15T08:11:43.287380Z",
     "start_time": "2025-02-15T08:11:43.169381Z"
    }
   },
   "cell_type": "code",
   "source": [
    "net[0].weight.data.normal_(0, 0.01)\n",
    "net[0].bias.data.fill_(0)"
   ],
   "id": "86fb0e71ca02f843",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-15T08:12:47.233356Z",
     "start_time": "2025-02-15T08:12:47.114325Z"
    }
   },
   "cell_type": "code",
   "source": "loss = nn.MSELoss()",
   "id": "a6fafc31e06dadba",
   "outputs": [],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-15T08:14:36.049575Z",
     "start_time": "2025-02-15T08:14:33.735920Z"
    }
   },
   "cell_type": "code",
   "source": "trainer = torch.optim.SGD(net.parameters(), lr=0.03)",
   "id": "4946841b413de8e5",
   "outputs": [],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-15T09:37:02.401821Z",
     "start_time": "2025-02-15T09:37:01.790894Z"
    }
   },
   "cell_type": "code",
   "source": [
    "num_epochs = 3\n",
    "for epoch in range(num_epochs):\n",
    "    for X, y in data_iter:\n",
    "        l = loss(net(X) ,y)\n",
    "        trainer.zero_grad()\n",
    "        l.backward()\n",
    "        trainer.step()\n",
    "    l = loss(net(features), labels)\n",
    "    print(f'epoch {epoch + 1}, loss {l:f}')"
   ],
   "id": "ccf13bd0c9c401fd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.000555\n",
      "epoch 2, loss 0.000103\n",
      "epoch 3, loss 0.000103\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-15T09:41:18.510901Z",
     "start_time": "2025-02-15T09:41:18.357709Z"
    }
   },
   "cell_type": "code",
   "source": [
    "w = net[0].weight.data\n",
    "print('w的估计误差：', true_w - w.reshape(true_w.shape))\n",
    "b = net[0].bias.data\n",
    "print('b的估计误差：', true_b - b)"
   ],
   "id": "3c61a60cc328b5d8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "w的估计误差： tensor([0.0006, 0.0002])\n",
      "b的估计误差： tensor([4.2439e-05])\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "c709ccf1375f59c5"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
